// API基础配置
const API_BASE_URL = '/api'

// 通用请求函数
async function request(url, options = {}) {
  const config = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers
    },
    ...options
  }

  try {
    const response = await fetch(`${API_BASE_URL}${url}`, config)
    
    if (!response.ok) {
      const error = new Error(`HTTP ${response.status}: ${response.statusText}`)
      error.status = response.status
      throw error
    }

    const contentType = response.headers.get('content-type')
    if (contentType && contentType.includes('application/json')) {
      return await response.json()
    } else {
      return await response.text()
    }
  } catch (error) {
    console.error('API请求失败:', error)
    throw error
  }
}

// GET请求
export function get(url, params = {}) {
  const queryString = new URLSearchParams(params).toString()
  const fullUrl = queryString ? `${url}?${queryString}` : url
  
  return request(fullUrl, {
    method: 'GET'
  })
}

// POST请求
export function post(url, data = {}) {
  return request(url, {
    method: 'POST',
    body: JSON.stringify(data)
  })
}

// PUT请求
export function put(url, data = {}) {
  return request(url, {
    method: 'PUT',
    body: JSON.stringify(data)
  })
}

// DELETE请求
export function del(url) {
  return request(url, {
    method: 'DELETE'
  })
}

// 系统状态API
export const systemAPI = {
  // 获取系统状态
  getStatus: () => get('/status'),
  
  // 获取系统日志
  getLogs: (params = {}) => get('/logs', params),
  
  // 重启系统
  restart: (data = {}) => post('/system/restart', data)
}

// 配置管理API
export const configAPI = {
  // 获取MQTT配置
  getMqttConfig: () => get('/config/mqtt'),
  
  // 更新MQTT配置
  updateMqttConfig: (config) => put('/config/mqtt', config),
  
  // 获取Modbus配置
  getModbusConfig: () => get('/config/modbus'),
  
  // 更新Modbus配置
  updateModbusConfig: (config) => put('/config/modbus', config),
  
  // 获取设备配置
  getDeviceConfig: () => get('/config/devices'),
  
  // 更新设备配置
  updateDeviceConfig: (config) => put('/config/devices', config),
  
  // 获取系统配置
  getSystemConfig: () => get('/config/system'),
  
  // 更新系统配置
  updateSystemConfig: (config) => put('/config/system', config)
}

// MQTT工具API
export const mqttAPI = {
  // 测试连接（传递当前表单配置，或不传使用后端配置）
  testConnection: (config) => post('/mqtt/test', config || {})
}

// Modbus工具API
export const modbusAPI = {
  // 测试Modbus设备连接
  testConnection: (config) => post('/modbus/test', config || {}),
  
  // 测试设备连接
  testDevice: (device) => post('/modbus/test', device),

  // 获取串口列表
  listSerialPorts: () => get('/modbus/serial-ports')
}

// 协议管理API
export const protocolAPI = {
  // 获取协议列表
  getProtocolList: () => get('/protocols'),
  
  // 获取协议内容
  getProtocol: (name) => get(`/protocols/${name}`),
  
  // 创建协议
  createProtocol: (name, data) => post(`/protocols/${name}`, data),
  
  // 更新协议
  updateProtocol: (name, data) => put(`/protocols/${name}`, data),
  
  // 删除协议
  deleteProtocol: (name) => del(`/protocols/${name}`)
}

// 设备管理API
export const deviceAPI = {
  // 测试设备连接
  testConnection: (deviceId) => post(`/devices/test/${deviceId}`),
  
  // 获取设备状态
  getDeviceStatus: (deviceId) => get(`/devices/status/${deviceId}`)
}

// 调度可视化API
export const dispatchAPI = {
  getStatus: () => get('/dispatch/status'),
  getControl: () => get('/dispatch/control'),
  setControl: (enabled) => post('/dispatch/control', { enabled })
}

// 错误处理辅助函数
export function handleApiError(error) {
  let message = '操作失败'
  
  if (error.status) {
    switch (error.status) {
      case 400:
        message = '请求参数错误'
        break
      case 401:
        message = '未授权访问'
        break
      case 403:
        message = '权限不足'
        break
      case 404:
        message = '资源不存在'
        break
      case 500:
        message = '服务器内部错误'
        break
      case 502:
        message = '服务器网关错误'
        break
      case 503:
        message = '服务不可用'
        break
      default:
        message = error.message || '未知错误'
    }
  } else if (error.message) {
    message = error.message
  }
  
  return message
}
